package com.app.ui.activity.account;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import com.app.net.res.user.User;
import com.app.ui.activity.HomeActivity;
import com.app.ui.activity.action.BaseBarActivity;
import com.app.utiles.other.ActivityUtile;
import com.app.utiles.other.StringUtile;
import com.app.utiles.other.ToastUtile;
import com.wxj.zx.R;

import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.listener.SaveListener;

/**
 * Created by Administrator on 2016/2/15.
 */
public class LoginActivity extends BaseBarActivity {
    private EditText passwordEt;
    private EditText phoneEt;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        phoneEt = (EditText) findViewById(R.id.login_phone_et);
        passwordEt = (EditText) findViewById(R.id.login_passwowd_et);

    }

    private String phone;
    private String password;


    @OnClick({R.id.login_register_tv, R.id.login_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.login_btn:
                phone = phoneEt.getText().toString();
                password = passwordEt.getText().toString();
                if (!StringUtile.isPhone(phone)) {
                    ToastUtile.showToast("请输入正确的手机号");
                    return;
                }
                if (TextUtils.isEmpty(password) || password.length() < 6) {
                    ToastUtile.showToast("请输入6-20位密码");
                    return;
                }
                dialogShow();
                login(phone, password);
                break;
            case R.id.login_register_tv:
                ActivityUtile.startActivityCommon(RegisterActivity.class);
                break;
        }
    }

    public void login(String phone, String password) {
        User user = new User();
        user.setUsername(phone);
        user.setPassword(password);
        user.login(this, new LoginListener());

    }

    class LoginListener extends SaveListener {

        @Override
        public void onSuccess() {
            dialogDismiss();
            User user = BmobUser.getCurrentUser(LoginActivity.this, User.class);
            baseApplication.setUser(user);
            ActivityUtile.startActivityCommon(HomeActivity.class);
            finish();
        }

        @Override
        public void onFailure(int i, String s) {
            dialogDismiss();
            ToastUtile.showToast("登录失败");
        }
    }

}
